<template>
  <div class="personBill">
    <el-card shadow="hover" class="pcOnly" style="margin-bottom: 20px">
      <el-form :inline="true" label-width="80">
        <el-form-item label="分类">
          <el-select
              v-model="formInline.category"
          >
            <el-option label="所有" :value="-1"/>
            <el-option :label="value.name" :value="key" v-for="(value, key, index) in categoryTypes"/>
          </el-select>
        </el-form-item>
        <el-form-item label="金额">
          <el-select
              v-model="formInline.amountLimit"
          >
            <el-option label="所有" :value="0"/>
            <el-option label="小于100" :value="1"/>
            <el-option label="100-500" :value="2"/>
            <el-option label="500-1000" :value="3"/>
            <el-option label="1000+" :value="4"/>
          </el-select>
        </el-form-item>
        <el-form-item label="支出/收入">
          <el-select
              v-model="formInline.isOut"
          >
            <el-option label="所有" :value="-1"/>
            <el-option label="收入" :value="0"/>
            <el-option label="支出" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否删除">
          <el-select
              v-model="formInline.isDelete"
          >
            <el-option label="未删除" :value="0"/>
            <el-option label="已删除" :value="1"/>
            <el-option label="所有" :value="-1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="完成状态">
          <el-select
              v-model="formInline.isComplete"
              placeholder="请选择账单的完成状态"
          >
            <el-option label="完成" :value="1"/>
            <el-option label="未完成" :value="0"/>
            <el-option label="全部" :value="-1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="账单时间">
          <el-date-picker
              v-model="formInline.billTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY/MM/DD"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="resetFormData">重置</el-button>
          <el-button type="success" @click="handleBillMessageAdd">记账</el-button>
          <el-button type="danger" @click="showCategoryDialog">账单类型管理</el-button>
          <el-button type="warning" @click="showCreateCategoryDialog">创建账单类型</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
          <!--<el-button type="danger" @click="">删除选中</el-button>-->
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover" class="pcOnly" style="flex: 1" body-style="display:flex;height:100%;overflow:hidden">
      <div style="flex:1 ;overflow: auto">
        <el-table :data="tableData" border fit show-summary v-loading="showLoading">
          <el-table-column :prop="item.dataKey" :label="item.title" :width="item.width" resizable show-overflow-tooltip
                           v-for="item in tableHeader"/>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="scope">
              <el-popconfirm
                  width="220"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  :icon="RemoveFilled"
                  icon-color="red"
                  title="确定要删除该账单嘛?"
                  @confirm="handleDelete(scope.$index, scope.row)"
              >
                <template #reference>
                  <el-button v-if="scope.row.isDelete === '否'" link type="primary" size="small">删除</el-button>
                </template>
              </el-popconfirm>
              <el-button link type="primary" size="small" @click="handleBillMessageUpdate(scope.$index, scope.row)">
                修改
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <bill-dialog
        :title="title"
        :bill-data="dialogBillData"
        v-model:visible="showBillMessageDialog"
        :is-company="false"
        :is-update="isUpdate"
        :category-types="categoryTypes"
        @confirm="handleBillMessageConfirm"
        @cancel="handleBillMessageClose"
    />
    <category-manage-dialog
        v-model:visible="categoryDialogVisible"
        title="个人分类管理"
        :is-company="false"
    />
    <create-category-dialog
        v-model:visible="createCategoryDialogVisible"
        title="创建个人账单分类"
        :is-company="false"
    />
    <el-button class="mobileOnly" type="success" @click="handleBillMessageAdd">记账</el-button>
    <el-button class="mobileOnly" type="success" @click="handleExport">导出</el-button>
  </div>
</template>

<script setup>
import {
  getPersonBillCategoryRef,
  getPersonBillRef,
  usePersonBillAdd,
  usePersonBillDelete,
  usePersonBillUpdate
} from "@/composition/billSys/usePersonBill.js";
import dayjs from "dayjs";
import BillDialog from "@/components/billDialog.vue";
import CategoryManageDialog from "@/components/categoryManageDialog.vue";
import CreateCategoryDialog from "@/components/createCategoryDialog.vue";
import {RemoveFilled} from "@element-plus/icons-vue";
import {elTip, exportCsv} from "@/utils/index.js";

const formInlineTemp = {
  date: '',
  isDelete: 0,
  isComplete: -1,
  amountLimit: 0,
  category: -1,
  isOut: -1,
  billTime: '',
};

const formInline = ref({...formInlineTemp});

const resetFormData = () => {
  formInline.value = {...formInlineTemp};
  search();
};


// --------------------table-----------------

const showLoading = ref(false);

// 获取分类类型
const categoryTypes = getPersonBillCategoryRef();

// 定义金额
const amountLimitData = {
  0: null,
  1: [0, 100],
  2: [100, 500],
  3: [500, 1000],
  4: [1000, Number.MAX_SAFE_INTEGER],
};

// 定义table 表头
const tableHeader = [
  {
    dataKey: `billTime`,
    title: `账单时间`,
    width: 120
  },
  {
    dataKey: `category`,
    title: `类别`,
    width: 120
  },
  {
    dataKey: `amount`,
    title: `金额`,
    width: 120
  },
  {
    dataKey: `isDelete`,
    title: `是否删除`,
    width: 120
  },
  {
    dataKey: `isComplete`,
    title: `是否完成`,
    width: 120
  },
  {
    dataKey: `isOut`,
    title: `支出/收入`,
    width: 120
  },
  {
    dataKey: `remark`,
    title: `备注`,
  },
  {
    dataKey: `date`,
    title: `创建时间`,
    width: 120
  },
];

// 定义表单数据
const personBillCategory = getPersonBillCategoryRef();
const personBillRef = getPersonBillRef();
const tableData = ref([]);

// 数据过滤
const tableDataFilter = (item) => {
  let {billTime, isDelete, isComplete, amountLimit, category, isOut} = formInline.value;
  if (billTime !== '') {
    let start = billTime[0].getTime();
    let end = billTime[1].getTime() + 24 * 60 * 60 * 1000;
    let now = Number(item.billTime);
    // console.log(now, start, end, item);
    if (now < start || now > end) {
      return false;
    }
  }
  if (isDelete !== -1 && item.isDelete !== isDelete) {
    return false;
  }
  if (isComplete !== -1 && item.isComplete !== isComplete) {
    return false;
  }
  if (amountLimit !== 0 && (Number(item.amount) < amountLimitData[amountLimit][0] || Number(item.amount) > amountLimitData[amountLimit][1])) {
    return false;
  }
  if (category !== -1 && Number(item.category) !== Number(category)) {
    return false;
  }
  if (isOut !== -1 && personBillCategory.value[item.category].isOut !== isOut) {
    return false;
  }
  return true;
};
// 获取过滤完成的数据
const getTableFilterData = () => {
  return personBillRef.value.filter(tableDataFilter).sort((a, b) => {
    // 根据billTime 从达到小排序
    return Number(b.billTime) - Number(a.billTime);
  }).map(item => {
    return {
      id: item.id,
      category: (personBillCategory.value[item.category] && personBillCategory.value[item.category].name) || item.category,
      amount: item.amount,
      remark: item.remark,
      date: dayjs(Number(item.createTime)).format('YYYY-MM-DD'),
      isDelete: item.isDelete === 0 ? '否' : '是',
      isComplete: item.isComplete === 0 ? '否' : '是',
      isOut: (personBillCategory.value[item.category] && (personBillCategory.value[item.category].isOut ? '支出' : '收入')) || '已删除',
      billTime: dayjs(Number(item.billTime)).format('YYYY-MM-DD'),
    };
  });
};
watch([() => personBillRef.value, () => personBillCategory.value], () => {
  if (personBillRef.value.length === 0 || Object.keys(personBillCategory.value).length === 0) {
    return;
  }
  tableData.value = getTableFilterData();
}, {deep: true});

// 条件查询
const search = () => {
  console.log('search', formInline.value);
  tableData.value = getTableFilterData();
};

// 删除数据
const handleDelete = async (index, rowData) => {
  let billid = rowData.id;
  showLoading.value = true;
  try {
    await usePersonBillDelete(billid);
  } catch (e) {
    console.log(e);
  }
  showLoading.value = false;
};

onMounted(() => {
  console.log('personbill mounted');
  search();
});

// --------------------bill-dialog-----------------

const dialogBillDataTemp = {
  id: -1,
  category: '',
  amount: null,
  remark: '',
  date: dayjs(new Date()).format('YYYY-MM-DD'),
  isDelete: 0,
  isComplete: 1,
  isOut: 1,
  billTime: ''
};
const showBillMessageDialog = ref(false);
const title = ref('添加账单');
const dialogBillData = ref({...dialogBillDataTemp});
const isUpdate = ref(false);

// 确认事件
const handleBillMessageConfirm = (value) => {
  // 修改
  if (isUpdate.value) {
    usePersonBillUpdate(value.id, value.category, value.remark, value.amount, value.isComplete, value.billTime);
    return elTip('修改账单成功');
  }
  // 增加 增加账单
  usePersonBillAdd(value.category, value.remark, value.amount, value.isComplete, value.billTime);
  elTip('添加账单成功');
};
// 关闭回调
const handleBillMessageClose = () => {
  // 目前好像不需要
  dialogBillData.value = {...dialogBillDataTemp};
};

// 打开dialog update
const handleBillMessageUpdate = (index, rowData) => {
  if (rowData) {
    isUpdate.value = true;
    let bill = personBillRef.value.find(item => item.id === rowData.id);
    bill.category = bill.category.toString();
    dialogBillData.value = {...bill};
    title.value = '修改账单';
    showBillMessageDialog.value = true;
  }
};

// 打开dialog add
const handleBillMessageAdd = () => {
  isUpdate.value = false;
  dialogBillData.value = {...dialogBillDataTemp};
  title.value = '添加账单';
  showBillMessageDialog.value = true;
};

// --------------------category-manage-dialog-----------------

const categoryDialogVisible = ref(false);
const showCategoryDialog = () => {
  categoryDialogVisible.value = true;
};

// --------------------create-category-dialog-----------------

const createCategoryDialogVisible = ref(false);

const showCreateCategoryDialog = () => {
  createCategoryDialogVisible.value = true;
};

// --------------------export-----------------

const handleExport = () => {
  exportCsv(tableHeader.map((item) => {
    return {
      title: item.title,
      key: item.dataKey
    };
  }), tableData.value, '个人账单-'+dayjs(new Date()).format('YYYY-MM-DD'));
};
</script>

<style scoped lang="scss">
.el-input {
  --el-input-width: 220px;
}

.el-select {
  --el-select-width: 220px;
}

.personBill {
  width: 100%;
  height: calc(100% - 50px - 33px);
  padding: 10px;
  background-color: $bg-color-gray;
  display: flex;
  flex-direction: column;
  justify-content: center;
  //align-items: center;
}
</style>
